package cn.bby.tools.utils;

import com.intellij.openapi.project.Project;
import com.intellij.terminal.ui.TerminalWidget;
import org.jetbrains.plugins.terminal.TerminalToolWindowManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @description: TerminalUtil
 * @author: bby
 * @date: 2025/10/28 11:51
 * @version: 1.0
 */
public class TerminalUtil {
    private static TerminalWidget terminalWidget;

    public static void executeCommand(Project project, String curlCmd) {
        if (terminalWidget == null || terminalWidget.getTtyConnector() == null
                || !terminalWidget.getTtyConnector().isConnected()) {
            terminalWidget = TerminalToolWindowManager.getInstance(project)
                    .createShellWidget(project.getBasePath(), "exe", true, false);
        }
        terminalWidget.sendCommandToExecute(curlCmd);
    }



    public static String executeCommandDirect(String command) {
        try {
            // 创建进程执行curl命令
            ProcessBuilder processBuilder = new ProcessBuilder();
            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                processBuilder.command("cmd.exe", "/c", command);
            } else {
                processBuilder.command("sh", "-c", command);
            }
            
            Process process = processBuilder.start();
            
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            
            // 等待命令执行完成
            int exitCode = process.waitFor();
            
            if (exitCode != 0) {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder errorOutput = new StringBuilder();
                String errorLine;
                
                while ((errorLine = errorReader.readLine()) != null) {
                    errorOutput.append(errorLine).append("\n");
                }
                
                return "Command failed with exit code " + exitCode + ": " + errorOutput.toString();
            }
            
            return output.toString();

        } catch (Exception ex) {
            return "Error executing command: " + ex.getMessage();
        }
    }
}
